package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.util.FastDFSClient;
import com.changgou.file.util.FastDFSFile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

@RestController
@RequestMapping("/file")
public class FileController {
    @PostMapping("/upload")
    public Result uploadFile(MultipartFile file){

        try {
            if (file==null){
                throw new RuntimeException("文件为空");
            }
            if (file.getOriginalFilename()==null){
                throw new RuntimeException("文件名为空");
            }
            String originalFilename = file.getOriginalFilename();
            byte[] fileBytes = file.getBytes();
            int i = originalFilename.lastIndexOf(".")+1;
            String substring = originalFilename.substring(i);

            FastDFSFile fileff = new FastDFSFile(originalFilename,fileBytes,substring);
            //1 FastDFsClient 的 upload 方法为静态方法直接上传  参数需要FastDFSFile
            String[] upload = FastDFSClient.upload(fileff);
            //拼接给用户返回的图片的url 使其可以直接访问
            String url = FastDFSClient.getTrackerUrl()+upload[0]+"/"+upload[1];
            return new Result(true,StatusCode.OK,"上传成功",url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, StatusCode.ERROR,"上传失败");
    }

    @GetMapping("/download")
    public Result downloadFile(){

        try {
            //http://192.168.200.128:8080/group1/M00/00/00/wKjIgF5M-bWAMZneAACRT5_emVg279.jpg
            InputStream inputStream = FastDFSClient.downFile("group1", "M00/00/00/wKjIgF5M-bWAMZneAACRT5_emVg279.jpg");
            byte bytes[] = new byte[1024];
            FileOutputStream fileOutputStream = new FileOutputStream("D://123.jpg");
            int i=0;
            while ((i=inputStream.read(bytes))!= -1){
                fileOutputStream.write(i);
            }
            inputStream.close();
            fileOutputStream.close();
            return new Result(true,StatusCode.OK,"下载成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, StatusCode.ERROR,"上传失败");
    }
}
